#include <dbg.h>

#include <cassert>
using namespace std;

class Solution {
public:
    int longestSubarray(vector<int>& nums) {
        int res = 0;
        int left = 0;
        int zeroNum = 0;  // 记录窗口内0的个数
        for (int right = 0; right < nums.size(); ++right) {
            if (nums[right] == 0) {
                ++zeroNum;
            }
            while (zeroNum > 1) {  // 窗口内0的个数大于1，就需要缩小窗口
                if (nums[left] == 0) {
                    --zeroNum;
                }
                ++left;
            }
            res = max(res, right - left);
        }
        return res;
    }
};

int main() {
    Solution s;

    vector<int> nums1{1, 1, 0, 1};
    vector<int> nums2{0, 1, 1, 1, 0, 1, 1, 0, 1};
    vector<int> nums3{1, 1, 1};

    assert(s.longestSubarray(nums1) == 3);
    assert(s.longestSubarray(nums2) == 5);
    assert(s.longestSubarray(nums3) == 2);

    return 0;
}